<template>
  <div 
    class="floating-robot-container"
    :style="{ left: robotPosition.x + 'px', top: robotPosition.y + 'px' }"
    @mousedown="startDrag"
  >
    <!-- 悬浮机器人头像 -->
    <div 
      class="robot-avatar" 
      :class="{ 'active': isChatOpen, 'pulse': hasNewMessage, 'dragging': isDragging }"
      @click="toggleChat"
    >
      <div class="robot-face">
        <!-- 机器人头部装饰 -->
        <div class="robot-head">
          <div class="robot-antenna"></div>
        </div>
        <!-- 机器人眼睛 -->
        <div class="robot-eyes">
          <div class="eye left-eye" :class="{ 'blink': isBlinking }">
            <div class="eye-shine"></div>
          </div>
          <div class="eye right-eye" :class="{ 'blink': isBlinking }">
            <div class="eye-shine"></div>
          </div>
        </div>
        <!-- 机器人嘴巴 -->
        <div class="robot-mouth" :class="{ 'talking': isTyping }">
          <div class="mouth-inner"></div>
        </div>
        <!-- 机器人脸颊 -->
        <div class="robot-cheek left-cheek"></div>
        <div class="robot-cheek right-cheek"></div>
      </div>
      
      <!-- 状态指示器 -->
      <div class="status-indicator" :class="statusClass"></div>
      
     
    </div>

    <!-- 聊天窗口 -->
    <div 
      class="chat-window centered" 
      :class="{ 'open': isChatOpen }"
    >
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="agent-info">
          <div class="agent-avatar">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="agent-details">
            <h3>小智</h3>
            <span class="status online">在线</span>
          </div>
        </div>
        <div class="header-actions">
          <el-button size="small" @click="clearChat" circle title="清空对话">
            <el-icon><Delete /></el-icon>
          </el-button>
          <el-button size="small" @click="toggleChat" circle title="关闭">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainer">
        <div 
          v-for="message in messages" 
          :key="message.id"
          class="message-item"
          :class="{ 'user-message': message.isFromUser, 'bot-message': !message.isFromUser }"
        >
          <div class="message-avatar" v-if="!message.isFromUser">
            <el-icon><ChatDotRound /></el-icon>
          </div>
          <div class="message-content">
            <div class="message-bubble">
              <div class="message-text" v-html="formatMessage(message.message || '')"></div>
              <div class="message-time">{{ formatTime(message.timestamp) }}</div>
            </div>
          </div>
          <div class="message-avatar" v-if="message.isFromUser">
            <el-icon><User /></el-icon>
          </div>
        </div>

        <!-- 输入中指示器 -->
        <div v-if="isTyping" class="typing-indicator">
          <div class="typing-dots">
            <span></span>
            <span></span>
            <span></span>
          </div>
          <span class="typing-text">小智正在思考...</span>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <div class="input-container">
          <el-input
            v-model="inputMessage"
            placeholder="请输入您的问题..."
            @keyup.enter="sendMessage"
            :disabled="isTyping"
            class="message-input"
          >
            <template #append>
              <el-button 
                @click="sendMessage" 
                :disabled="!inputMessage.trim() || isTyping"
                type="primary"
              >
                <el-icon><Promotion /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        
        <!-- 快捷操作 -->
        <div class="quick-actions">
          <el-button size="small" @click="sendQuickMessage('库存查询')">库存查询</el-button>
          <el-button size="small" @click="sendQuickMessage('订单状态')">订单状态</el-button>
          <el-button size="small" @click="sendQuickMessage('仓库操作')">仓库操作</el-button>
          <el-button size="small" @click="sendQuickMessage('客服使用手册')">客服使用手册</el-button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  ChatDotRound, 
  User, 
  Promotion, 
  Delete, 
  Close 
} from '@element-plus/icons-vue';
import { useCustomerServiceApi, type CustomerServiceMessage } from '/@/api/customerService';

// API服务
const customerServiceApi = useCustomerServiceApi();

// 响应式数据
const isChatOpen = ref(false);
const isTyping = ref(false);
const isTransferring = ref(false);
const isCreatingWorkOrder = ref(false);
const hasNewMessage = ref(false);
const isBlinking = ref(false);
const inputMessage = ref('');
const conversationId = ref('');
const messages = ref<CustomerServiceMessage[]>([]);
const showWorkOrderDialog = ref(false);
const messagesContainer = ref<HTMLElement>();

// 拖拽相关
const isDragging = ref(false);
const robotPosition = ref({ 
  x: Math.max(20, window.innerWidth - 100), 
  y: Math.max(20, window.innerHeight - 100) 
});
const dragStart = ref({ x: 0, y: 0 });
const dragOffset = ref({ x: 0, y: 0 });

// 工单表单
const workOrderForm = reactive({
  title: '',
  description: '',
  priority: 'medium',
  category: 'technical'
});

// 计算属性
const statusClass = computed(() => {
  if (isTyping.value) return 'typing';
  if (isTransferring.value) return 'transferring';
  return 'online';
});

// 聊天窗口现在通过CSS类控制位置，无需JavaScript计算

// 生命周期
onMounted(() => {
  initChat();
  startBlinkingAnimation();
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleWindowResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleWindowResize);
});

// 窗口大小变化处理
const handleWindowResize = () => {
  // 确保机器人位置在屏幕范围内
  const robotSize = 60;
  robotPosition.value.x = Math.max(20, Math.min(window.innerWidth - robotSize - 20, robotPosition.value.x));
  robotPosition.value.y = Math.max(20, Math.min(window.innerHeight - robotSize - 20, robotPosition.value.y));
  
  // 聊天窗口会自动通过计算属性重新居中，无需额外处理
};

// 监听消息变化
watch(messages, () => {
  hasNewMessage.value = true;
  nextTick(() => {
    scrollToBottom();
  });
}, { deep: true });

// 方法
const toggleChat = () => {
  isChatOpen.value = !isChatOpen.value;
  if (isChatOpen.value) {
    hasNewMessage.value = false;
    // 确保DOM更新后再执行滚动
    setTimeout(() => {
      nextTick(() => {
        // 如果是初始状态（只有欢迎消息），滚动到顶部显示完整的欢迎消息
        if (messages.value.length <= 1) {
          scrollToTop();
        } else {
          scrollToBottom();
        }
      });
    }, 100);
  }
};

// 拖拽相关方法
const startDrag = (e: MouseEvent) => {
  // 如果点击的是聊天窗口，不启动拖拽
  if ((e.target as HTMLElement).closest('.chat-window')) {
    return;
  }
  
  isDragging.value = true;
  dragStart.value = { x: e.clientX, y: e.clientY };
  dragOffset.value = { 
    x: e.clientX - robotPosition.value.x, 
    y: e.clientY - robotPosition.value.y 
  };
  
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  
  // 阻止默认行为
  e.preventDefault();
};

const onDrag = (e: MouseEvent) => {
  if (!isDragging.value) return;
  
  const newX = e.clientX - dragOffset.value.x;
  const newY = e.clientY - dragOffset.value.y;
  
  // 限制在屏幕范围内
  const robotSize = 60;
  robotPosition.value.x = Math.max(0, Math.min(window.innerWidth - robotSize, newX));
  robotPosition.value.y = Math.max(0, Math.min(window.innerHeight - robotSize, newY));
};

const stopDrag = () => {
  isDragging.value = false;
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
};

const initChat = () => {
  conversationId.value = `conv_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

  // 添加欢迎消息
  const welcomeMessage: CustomerServiceMessage = {
    id: 1,
    userId: 0,
    userName: '小智',
    message: '你好呀~我是小智！✨ 很高兴为您服务！我是您的专属WMS智能助手，可以帮您处理库存查询、订单问题、仓库操作等业务。有什么可以帮助您的吗？😊',
    messageType: 'text',
    timestamp: new Date().toISOString(),
    isFromUser: false,
    conversationId: conversationId.value
  };

  messages.value.push(welcomeMessage);
  
  // 不需要初始化时滚动，让聊天窗口自然显示在顶部
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isTyping.value) return;

  const userMessage: CustomerServiceMessage = {
    id: Date.now(),
    userId: 1,
    userName: '用户',
    message: inputMessage.value.trim(),
    messageType: 'text',
    timestamp: new Date().toISOString(),
    isFromUser: true,
    conversationId: conversationId.value
  };

  messages.value.push(userMessage);
  const currentMessage = inputMessage.value;
  inputMessage.value = '';
  isTyping.value = true;

  try {
    const apiResponse = await customerServiceApi.sendMessage({
      message: currentMessage,
      conversationId: conversationId.value,
      userId: 1,
      userName: '用户'
    });

    // 处理API响应数据
    const response = apiResponse.data?.result || apiResponse.data || apiResponse;
    
    const agentResponse: CustomerServiceMessage = {
      id: Date.now() + 1,
      userId: 0,
      userName: '小智',
      message: response.message || '抱歉，我暂时无法回复您的消息。',
      messageType: 'text',
      timestamp: new Date().toISOString(),
      isFromUser: false,
      conversationId: conversationId.value,
      actions: response.actions
    };

    messages.value.push(agentResponse);

    // 如果AI建议创建工单，显示工单创建对话框
    if (response.workOrderCreated || response.actions?.some(action => action.type === 'create_work_order')) {
      showWorkOrderDialog.value = true;
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    
    // 添加错误消息到聊天记录
    const errorResponse: CustomerServiceMessage = {
      id: Date.now() + 1,
      userId: 0,
      userName: '小智',
      message: '抱歉，服务暂时不可用，请稍后重试或转接人工客服。',
      messageType: 'text',
      timestamp: new Date().toISOString(),
      isFromUser: false,
      conversationId: conversationId.value
    };
    messages.value.push(errorResponse);
    
    ElMessage.error('发送消息失败，请稍后重试');
  } finally {
    isTyping.value = false;
  }
};

const sendQuickMessage = (message: string) => {
  inputMessage.value = message;
  sendMessage();
};

const clearChat = async () => {
  try {
    // 临时降低聊天窗口的 z-index
    const chatWindow = document.querySelector('.chat-window.centered') as HTMLElement;
    const originalZIndex = chatWindow ? chatWindow.style.zIndex : '';
    
    if (chatWindow) {
      chatWindow.style.zIndex = '1000';
    }
    
    try {
      await ElMessageBox.confirm('确定要清空对话记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass: 'clear-chat-dialog',
        appendToBody: true,
        zIndex: 20000
      });
      
      messages.value = [];
      initChat();
      ElMessage.success('对话已清空');
    } finally {
      // 恢复聊天窗口的 z-index
      if (chatWindow) {
        chatWindow.style.zIndex = originalZIndex || '2000';
      }
    }
  } catch {
    // 用户取消
  }
};

const transferToHuman = async () => {
  isTransferring.value = true;
  
  try {
    const response = await customerServiceApi.transferToHuman({
      conversationId: conversationId.value,
      userId: 1,
      reason: '用户请求转接人工客服'
    });

    const transferResponse = response.data?.result || response.data || response;

    const transferMessage: CustomerServiceMessage = {
      id: Date.now(),
      userId: 0,
      userName: '小智',
      message: transferResponse.message,
      messageType: 'text',
      timestamp: new Date().toISOString(),
      isFromUser: false,
      conversationId: conversationId.value
    };

    messages.value.push(transferMessage);
    ElMessage.success('已为您转接人工客服');
  } catch (error) {
    console.error('转接失败:', error);
    ElMessage.error('转接失败，请稍后重试');
  } finally {
    isTransferring.value = false;
  }
};

const createWorkOrder = async () => {
  if (!workOrderForm.title.trim() || !workOrderForm.description.trim()) {
    ElMessage.warning('请填写工单标题和问题描述');
    return;
  }

  isCreatingWorkOrder.value = true;

  try {
    const response = await customerServiceApi.createWorkOrder({
      title: workOrderForm.title,
      description: workOrderForm.description,
      priority: workOrderForm.priority,
      category: workOrderForm.category,
      userId: 1,
      conversationId: conversationId.value
    });

    const workOrderResponse = response.data?.result || response.data || response;

    const workOrderMessage: CustomerServiceMessage = {
      id: Date.now(),
      userId: 0,
      userName: '小智',
      message: `工单创建成功！工单编号：${workOrderResponse.workOrderId}。我们的技术支持团队会尽快处理您的问题。`,
      messageType: 'text',
      timestamp: new Date().toISOString(),
      isFromUser: false,
      conversationId: conversationId.value
    };

    messages.value.push(workOrderMessage);
    showWorkOrderDialog.value = false;
    
    // 重置表单
    Object.assign(workOrderForm, {
      title: '',
      description: '',
      priority: 'medium',
      category: 'technical'
    });

    ElMessage.success('工单创建成功');
  } catch (error) {
    console.error('创建工单失败:', error);
    ElMessage.error('创建工单失败，请稍后重试');
  } finally {
    isCreatingWorkOrder.value = false;
  }
};

const handleAction = async (action: any) => {
  switch (action.type) {
    case 'create_work_order':
      showWorkOrderDialog.value = true;
      break;
    case 'transfer_to_human':
      await transferToHuman();
      break;
    case 'query_inventory':
      await sendQuickMessage('库存查询');
      break;
    case 'query_order':
      await sendQuickMessage('订单状态');
      break;
    default:
      console.log('未知操作类型:', action.type);
  }
};

const getActionType = (actionType: string) => {
  const typeMap: Record<string, string> = {
    'create_work_order': 'warning',
    'transfer_to_human': 'info',
    'query_inventory': 'success',
    'query_order': 'primary'
  };
  return typeMap[actionType] || 'default';
};

const getActionText = (actionType: string) => {
  const textMap: Record<string, string> = {
    'create_work_order': '创建工单',
    'transfer_to_human': '转人工客服',
    'query_inventory': '查询库存',
    'query_order': '查询订单'
  };
  return textMap[actionType] || actionType;
};

const formatMessage = (message: string) => {
  // 如果消息为空，返回空内容（避免显示占位符）
  if (!message || !message.trim()) {
    return '';
  }
  
  // 支持Markdown格式的消息格式化，类似RAGFLOW的回答格式
  let formattedMessage = message;
  
  // 处理换行
  formattedMessage = formattedMessage.replace(/\n/g, '<br>');
  
  // 处理粗体文本 **text**
  formattedMessage = formattedMessage.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
  
  // 处理标题 ### text
  formattedMessage = formattedMessage.replace(/^### (.*?)$/gm, '<h3 style="color: #409EFF; margin: 8px 0 4px 0; font-size: 14px;">$1</h3>');
  
  // 处理标题 ## text
  formattedMessage = formattedMessage.replace(/^## (.*?)$/gm, '<h2 style="color: #409EFF; margin: 10px 0 6px 0; font-size: 16px;">$1</h2>');
  
  // 处理标题 # text
  formattedMessage = formattedMessage.replace(/^# (.*?)$/gm, '<h1 style="color: #409EFF; margin: 12px 0 8px 0; font-size: 18px;">$1</h1>');
  
  // 处理列表项 - text
  formattedMessage = formattedMessage.replace(/^- (.*?)$/gm, '<div style="margin: 4px 0; padding-left: 16px; position: relative;"><span style="position: absolute; left: 0; color: #409EFF;">•</span>$1</div>');
  
  // 处理代码块 ```text```
  formattedMessage = formattedMessage.replace(/```(.*?)```/gs, '<pre style="background: #f5f5f5; padding: 8px; border-radius: 4px; margin: 8px 0; font-family: monospace; font-size: 12px;">$1</pre>');
  
  // 处理行内代码 `text`
  formattedMessage = formattedMessage.replace(/`(.*?)`/g, '<code style="background: #f5f5f5; padding: 2px 4px; border-radius: 2px; font-family: monospace; font-size: 12px;">$1</code>');
  
  return formattedMessage;
};

const formatTime = (timestamp: string) => {
  const date = new Date(timestamp);
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  });
};

const scrollToBottom = () => {
  if (messagesContainer.value) {
    // 使用多种方式确保滚动到底部
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    
    // 延迟再次滚动，确保内容加载完成
    setTimeout(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    }, 100);
    
    // 再次延迟滚动，确保所有内容都加载完成
    setTimeout(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
      }
    }, 300);
  }
};

const scrollToTop = () => {
  if (messagesContainer.value) {
    // 滚动到顶部，显示完整的初始消息
    messagesContainer.value.scrollTop = 0;
    
    // 延迟确保滚动生效
    setTimeout(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = 0;
      }
    }, 50);
    
    // 再次确保滚动
    setTimeout(() => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = 0;
      }
    }, 200);
  }
};

const startBlinkingAnimation = () => {
  setInterval(() => {
    isBlinking.value = true;
    setTimeout(() => {
      isBlinking.value = false;
    }, 150);
  }, 3000 + Math.random() * 2000); // 3-5秒随机眨眼
};
</script>

<style scoped>
.floating-robot-container {
  position: fixed;
  z-index: 2000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  user-select: none;
}

/* 悬浮机器人头像 */
.robot-avatar {
  width: 70px;
  height: 70px;
  background: linear-gradient(135deg, #FF6B9D 0%, #C44569 50%, #FF6B9D 100%);
  border-radius: 20px 20px 20px 5px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 30px rgba(255, 107, 157, 0.4), 
              0 0 0 4px rgba(255, 255, 255, 0.8),
              inset 0 2px 10px rgba(255, 255, 255, 0.3);
  transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
  border: none;
  overflow: hidden;
}

.robot-avatar::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: linear-gradient(45deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transform: rotate(45deg);
  animation: shine 3s infinite;
}

@keyframes shine {
  0% { transform: translateX(-100%) translateY(-100%) rotate(45deg); }
  100% { transform: translateX(100%) translateY(100%) rotate(45deg); }
}

.robot-avatar:hover {
  transform: scale(1.15) rotate(-5deg);
  box-shadow: 0 12px 40px rgba(255, 107, 157, 0.6),
              0 0 0 5px rgba(255, 255, 255, 0.9),
              inset 0 2px 15px rgba(255, 255, 255, 0.4);
  border-radius: 25px 25px 25px 8px;
}

.robot-avatar.active {
  background: linear-gradient(135deg, #00D4FF 0%, #0099CC 50%, #00D4FF 100%);
  transform: scale(1.1) rotate(3deg);
  box-shadow: 0 10px 35px rgba(0, 212, 255, 0.5),
              0 0 0 5px rgba(255, 255, 255, 0.9),
              inset 0 2px 12px rgba(255, 255, 255, 0.35);
}

.robot-avatar.pulse {
  animation: pulse 2s infinite, float 3s ease-in-out infinite;
}

.robot-avatar.dragging {
  cursor: grabbing;
  transform: scale(1.2) rotate(10deg);
  box-shadow: 0 15px 45px rgba(255, 107, 157, 0.7),
              0 0 0 6px rgba(255, 255, 255, 1);
}

@keyframes pulse {
  0%, 100% { 
    box-shadow: 0 8px 30px rgba(255, 107, 157, 0.4),
                0 0 0 4px rgba(255, 255, 255, 0.8),
                inset 0 2px 10px rgba(255, 255, 255, 0.3);
  }
  50% { 
    box-shadow: 0 8px 30px rgba(255, 107, 157, 0.7),
                0 0 0 6px rgba(255, 255, 255, 1),
                inset 0 2px 10px rgba(255, 255, 255, 0.5);
  }
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-8px); }
}

/* 机器人面部 */
.robot-face {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

/* 机器人头部装饰 */
.robot-head {
  position: absolute;
  top: -8px;
  width: 100%;
  height: 15px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.robot-antenna {
  width: 4px;
  height: 10px;
  background: linear-gradient(180deg, #fff 0%, rgba(255, 255, 255, 0.8) 100%);
  border-radius: 2px 2px 0 0;
  position: relative;
}

.robot-antenna::after {
  content: '';
  position: absolute;
  top: -4px;
  left: -2px;
  width: 8px;
  height: 8px;
  background: #fff;
  border-radius: 50%;
  box-shadow: 0 0 8px rgba(255, 255, 255, 0.8);
}

.robot-eyes {
  display: flex;
  gap: 12px;
  margin-bottom: 6px;
  margin-top: 8px;
  position: relative;
  z-index: 3;
}

.eye {
  width: 12px;
  height: 12px;
  background: #fff;
  border-radius: 50%;
  transition: all 0.15s ease;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2),
              inset 0 1px 2px rgba(255, 255, 255, 0.8);
}

.eye-shine {
  position: absolute;
  top: 2px;
  left: 3px;
  width: 4px;
  height: 4px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  box-shadow: 0 0 4px rgba(255, 255, 255, 0.8);
}

.eye.blink {
  height: 3px;
  border-radius: 2px;
}

.eye.blink .eye-shine {
  opacity: 0;
}

/* 机器人脸颊 */
.robot-cheek {
  position: absolute;
  width: 10px;
  height: 8px;
  background: rgba(255, 192, 203, 0.4);
  border-radius: 50%;
  bottom: 18px;
}

.left-cheek {
  left: 8px;
}

.right-cheek {
  right: 8px;
}

.robot-mouth {
  width: 20px;
  height: 12px;
  border: 2.5px solid #fff;
  border-top: none;
  border-radius: 0 0 20px 20px;
  transition: all 0.3s ease;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
}

.mouth-inner {
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 12px;
  height: 6px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 0 0 12px 12px;
}

.robot-mouth.talking {
  animation: talking 0.4s infinite alternate;
  height: 10px;
}

.robot-mouth.talking .mouth-inner {
  animation: mouthTalk 0.4s infinite alternate;
}

@keyframes talking {
  0% { 
    transform: scaleY(1);
    border-radius: 0 0 20px 20px;
  }
  100% { 
    transform: scaleY(0.6);
    border-radius: 0 0 15px 15px;
  }
}

@keyframes mouthTalk {
  0% { height: 6px; }
  100% { height: 2px; }
}

/* 状态指示器 */
.status-indicator {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  z-index: 10;
}

.status-indicator.online {
  background: #52c41a;
}

.status-indicator.typing {
  background: #1890ff;
  animation: typing-indicator 1s infinite;
}

.status-indicator.transferring {
  background: #faad14;
  animation: spin 1s linear infinite;
}

@keyframes typing-indicator {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 消息提示气泡 */
.message-bubble {
  position: absolute;
  bottom: 70px;
  right: 0;
  background: #ff4d4f;
  color: white;
  padding: 8px 12px;
  border-radius: 20px;
  font-size: 12px;
  white-space: nowrap;
  animation: bounce 2s infinite;
}

.message-bubble .bubble-tail {
  position: absolute;
  bottom: -6px;
  right: 20px;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #ff4d4f;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-10px); }
  60% { transform: translateY(-5px); }
}

/* 聊天窗口 */
.chat-window {
  position: absolute;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  border: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  transform: translateY(20px) scale(0.95);
  opacity: 0;
  visibility: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
  min-width: 0;
}

.chat-window.open {
  transform: translateY(0) scale(1);
  opacity: 1;
  visibility: visible;
}

/* 强制居中样式 - 在整个屏幕中间显示 */
.chat-window.centered {
  position: fixed !important;
  left: 50% !important;
  top: 50% !important;
  transform: translate(-50%, -50%) scale(0.95) !important;
  width: 480px !important;
  height: 700px !important;
  z-index: 2000 !important;
}

.chat-window.centered.open {
  transform: translate(-50%, -50%) scale(1) !important;
}

/* 聊天头部 */
.chat-header {
  padding: 12px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 16px 16px 0 0;
  flex-shrink: 0;
  z-index: 1;
  position: relative;
}

.agent-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.agent-avatar {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.agent-details h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.agent-details .status {
  font-size: 12px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-actions .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
}

.header-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 消息容器 */
.messages-container {
  flex: 1;
  padding-top: 90px;
  padding-left: 16px;
  padding-right: 16px;
  padding-bottom: 40px;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 0;
  scroll-behavior: smooth;
  align-items: stretch;
  justify-content: flex-start;
  position: relative;
  z-index: 0;
}

.messages-container::-webkit-scrollbar {
  width: 4px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 消息项 */
.message-item {
  display: flex;
  gap: 8px;
  align-items: flex-start;
}

.message-item.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 32px;
  height: 32px;
  background: #f5f5f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 0;
}

.user-message .message-content {
  align-items: flex-end;
}

.bot-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  background: #f5f5f5;
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  max-width: 100%;
  box-sizing: border-box;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: break-word;
  white-space: normal;
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.message-text {
  line-height: 1.4;
  word-wrap: break-word;
  overflow-wrap: break-word;
  word-break: break-word;
  color: #333333;
  white-space: normal;
  max-width: 100%;
}

.user-message .message-text {
  color: white !important;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
}

.user-message .message-time {
  color: rgba(255, 255, 255, 0.7);
}

/* 操作按钮 */
.message-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 8px;
}

.message-actions .el-button {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
}

/* 输入中指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: #f5f5f5;
  border-radius: 18px;
  max-width: 120px;
}

.typing-dots {
  display: flex;
  gap: 4px;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  background: #999;
  border-radius: 50%;
  animation: typing-dot 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing-dot {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

.typing-text {
  font-size: 12px;
  color: #666;
}

/* 输入区域 */
.input-area {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  border-radius: 0 0 16px 16px;
}

.input-container {
  margin-bottom: 12px;
}

.message-input {
  border-radius: 20px;
}

.message-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-input :deep(.el-input-group__append) {
  border-radius: 0 20px 20px 0;
}

.quick-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.quick-actions .el-button {
  font-size: 12px;
  padding: 4px 8px;
  height: auto;
  border-radius: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .robot-avatar {
    width: 50px;
    height: 50px;
  }
  
  .chat-window.centered {
    width: calc(100vw - 40px) !important;
    height: calc(100vh - 120px) !important;
    left: 50% !important;
    top: 50% !important;
    transform: translate(-50%, -50%) scale(0.95) !important;
  }
  
  .chat-window.centered.open {
    transform: translate(-50%, -50%) scale(1) !important;
  }
  
  .message-content {
    max-width: 85%;
  }
}

@media (max-width: 480px) {
  .chat-window {
    height: calc(100vh - 80px);
  }
  
  .quick-actions {
    justify-content: center;
  }
  
  .quick-actions .el-button {
    flex: 1;
    min-width: 0;
  }
}
</style>

<style>
/* 确保清空对话的确认框显示在聊天窗口上方 */
.clear-chat-dialog {
  z-index: 2500 !important;
}

.el-overlay {
  z-index: 2100 !important;
}

.el-overlay.clear-chat-dialog {
  z-index: 2500 !important;
}

.el-message-box.clear-chat-dialog {
  z-index: 2501 !important;
}

/* 针对 Element Plus 消息框的所有部分 */
body > div[class*="clear-chat-dialog"] {
  z-index: 2500 !important;
}

body > div[id*="el-overlay"] > .clear-chat-dialog {
  z-index: 2500 !important;
}

/* 确保消息文本内部的HTML元素也能正确换行 */
.message-text :deep(h1),
.message-text :deep(h2),
.message-text :deep(h3) {
  max-width: 100%;
  overflow-wrap: break-word;
  word-break: break-word;
  white-space: normal;
}

.message-text :deep(p),
.message-text :deep(div) {
  max-width: 100%;
  overflow-wrap: break-word;
  word-break: break-word;
  white-space: normal;
}

.message-text :deep(strong) {
  overflow-wrap: break-word;
  word-break: break-word;
}

.message-text :deep(pre) {
  white-space: pre-wrap;
  word-wrap: break-word;
  max-width: 100%;
  overflow-x: auto;
  overflow-wrap: break-word;
}

.message-text :deep(code) {
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
}
</style>